<template>
    <div class="roles">
        <el-row>
            <el-col>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-col>
            <el-col>
                <el-table :data="rolesList" border stripe row-key="id" :expand-row-keys="expands">
                    <el-table-column type="expand">
                        <template v-slot="scope">
                            <el-row :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']"
                                v-for="(item1, i1) in scope.row.children" :key="item1.id">
                                <el-col :span="5">
                                    <el-tag size="large" closable @close="removeRightById(scope.row, item1.id)">
                                        {{ item1.authName }}
                                    </el-tag>
                                    <el-icon>
                                        <CaretRight />
                                    </el-icon>
                                </el-col>
                                <el-col :span="19">
                                    <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                                        :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']">
                                        <el-col :span="6">
                                            <el-tag size="large" type="success" closable
                                                @close="removeRightById(scope.row, item2.id)">
                                                {{ item2.authName }}
                                            </el-tag>
                                            <el-icon>
                                                <CaretRight />
                                            </el-icon>
                                        </el-col>
                                        <el-col :span="18">
                                            <el-tag size="large" type="warning" :class="[i3 === 0 ? '' : 'bdtop']"
                                                v-for="(item3, i3) in item2.children" :key="item3.id" closable
                                                @close="removeRightById(scope.row, item3.id)">
                                                {{ item3.authName }}
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="#"></el-table-column>
                    <el-table-column prop="roleName" label="角色名称"></el-table-column>
                    <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                    <el-table-column label="操作" width="265px">
                        <template v-slot="scope">
                            <el-button size="small" type="primary" :icon="EditPen" @click="showEditDialog(scope.row)">
                                编辑
                            </el-button>
                            <el-button size="small" type="danger" :icon="Delete" @click="rolesdelete(scope.row.id)">
                                删除
                            </el-button>
                            <el-button size="small" type="warning" :icon="Setting"
                                @click="showSetRightDialog(scope.row)">
                                分配权限
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-dialog title="添加角色" v-model="addDialogVisible" @close="addRolesRef.resetFields()">
            <el-form :model="roleData" :rules="rules" ref="addRolesRef" label-width="30%">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="roleData.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="roleData.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addRolesUser(addRolesRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog title="修改角色" v-model="editDialogVisible" width="40%" @close="roleData={}">
            <el-form :model="roleData" :rules="rules" ref="editRolesRef" label-width="30%">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="roleData.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="roleData.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editFormInfo(editRolesRef)">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog title="分配权限" v-model="SetRightDialogVisible" width="50%" @close="SetRightDialogVisibleClosed">
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true"
                :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="SetRightDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="allotRights">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    import { reactive, ref } from "vue"
    import {
        ElButton,
        ElRow,
        ElCol,
        ElTag,
        ElTable,
        ElTableColumn,
        ElMessage,
        ElIcon,
        ElMessageBox,
        ElTree,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput

    } from "element-plus"
    import {
        Setting,
        EditPen,
        Delete,
        CaretRight
    } from '@element-plus/icons-vue'
    import {
        postAddRole,
        deleteRoles,
        jiaoshelb,
    fenpeijs,
    quanxianlb,
    scjszdqx,
    jsfpqx,
    } from "@/tools/ajax"
    import { useRules } from "@/tools/utils"
    const rolesList = reactive([])
    async function getRolesList() {
        const res = await jiaoshelb()
        rolesList.splice(0)
        rolesList.push(...res.data)
    }
    getRolesList() 
    const addDialogVisible = ref(false) 
    const roleData = ref({ 
        roleName: "",
        roleDesc: ""
    })
    const addRolesRef = reactive({}) 
    const { roleNameRule, roleDescRule } = useRules() 
    const rules = {
        roleName: roleNameRule,
        roleDesc: roleDescRule
    }
    function addRolesUser(form) {
        form.validate(async bool => {
            if (!bool) return ElMessage.warning("输入有误"); 
            const { meta: res } = await postAddRole(roleData.value)
            console.log(res);
            if (res.status != 201) return ElMessage.error(res.msg);
            ElMessage.success(res.msg);
            addDialogVisible.value = false;
            getRolesList() 
        })
    }
    const editDialogVisible = ref(false) 
    const editRolesRef = reactive(null) 
    function showEditDialog(data) { 
        console.log(data);
        roleData.value.id = data.id
        roleData.value.roleName = data.roleName
        roleData.value.roleDesc = data.roleDesc
        editDialogVisible.value = true
    }
    async function editFormInfo(form) {
        form.validate(async bool => {
            if (!bool) return ElMessage.warning("输入有误"); 
            const res = await fenpeijs(roleData.value)
            // console.log(res)
            if (res.meta.status !== 200) {
                return ElMessage.error(res.meta.msg)
            }
            ElMessage.success("角色信息已更新!")
            editDialogVisible.value = false
            getRolesList()
        })

    }

    async function rolesdelete(id) {
        const confirmRusult = await ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '永久删除该角色', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (confirmRusult !== 'confirm') {
            return ElMessage.info('已经取消了删除')
        }
        const res = await deleteRoles({ id })
        console.log(res)
        if (res.meta.status !== 200) {
            return ElMessage.error(res.meta.msg)
        }
        ElMessage.success(res.meta.msg)
        this.getRolesList()
    }
    const expands = reactive([])
    async function removeRightById(roles, rightId) {
        const confirmRusult = await ElMessageBox.confirm('此操作将删除角色的该权限, 是否继续?', '删除权限', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (confirmRusult !== 'confirm') {
            return ElMessage.info('已经取消了删除')
        }
        console.log(roles, rightId);
        expands[0] = roles.id
        const res = await scjszdqx({
            roleId: roles.id,
            rightId
        })
        console.log(res)
        if (res.meta.status !== 200) {
            return ElMessage.error(res.meta.msg)
        }
        ElMessage.success(res.meta.msg)
        roles.children = res.data 
    }
    const SetRightDialogVisible = ref(false)
    const treeRef = ref(null) 
    const rightsList = reactive([])  
    const treeProps = reactive({
        children: 'children',
        label: 'authName'
    })
    const defKeys = reactive([])
    var currentRoleId; 
    quanxianlb({ type: 'tree' }).then(res => {
        if (res.meta.status !== 200) {
            return ElMessage.error(res.meta.msg)
        }
        rightsList.push(...res.data)
        console.log(rightsList)
    })
    async function showSetRightDialog(roles) {
        getLeafKeys(roles)
        SetRightDialogVisible.value = true
        currentRoleId = roles.id  
    }
    function getLeafKeys(node) {
        node.children.forEach(item1 => {
            item1.children.forEach(item2 => {
                item2.children.forEach(item3 => {
                    defKeys.push(item3.id)
                })
            })
        })
        treeRef.value && treeRef.value.setCheckedKeys(defKeys)
    }
    async function allotRights() {
        const keys = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
        console.log(keys);
        const idStr = keys.join(',')
        var res = await fenpeijs({
            roleId: currentRoleId,
            rids: idStr
        })
        console.log(res);
        if (res.meta.status !== 200) {
            return ElMessage.error('分配权限失败!')
        }
        ElMessage.success('分配权限成功!')
        getRolesList()
        SetRightDialogVisible.value = false
    }
    function SetRightDialogVisibleClosed() {
        defKeys.splice(0)
    }
    // #endregion
</script>
<style scoped lang="scss">
    .el-col {
        text-align: left;
    }

    .el-table {
        margin-top: 15px;
    }

    .el-tag {
        margin: 7px;
    }

    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }

    .el-input {
        width: 80%;
    }
</style>